<script setup lang="ts">
import {
  priceModeMap,
  deliveryTypeMap,
  deliveryScopeMap,
  weightUnitMap,
} from './enums'
import {fenToYuan, yuanToFen} from '@/utils'
import {RegionPicker} from '@/views/universal/region'
import * as DineConfigApi from '@/api/dine/config/ConfigApi'
import {checkRole} from '@/utils/permission'

defineComponent({
  name: 'DineConfigForm'
})

const message = useMessage()

const formRef = ref()

// 表单数据模型
const formData = ref<any>({
  id: undefined,
  priceMode: 1,
  weightUnitName: '克',
  meatUnitPrice: 0,
  vegetableUnitPrice: 0,
  consumeThresholdPrice: 0,
  deliveryTypes: [0, 3],
  deliveryScope: 1,
  deliveryRadius: 0,
  deliveryAddresses: [
    {
      countyCode: '',
      detailAddress: ''
    }
  ],
  deliveryPrice: 100,
  deliveryFreeThresholdPrice: 1500,
  requireStapleFood: false,
  requireKitchenware: true,
  maxDailyOrders: 200
})

// 表单验证规则
const rules = {
  priceMode: [{required: true, message: '请选择计价模式', trigger: 'change'}],
  consumeThresholdPrice: [{required: true, message: '请输入最低消费金额', trigger: 'change'}],
  deliveryTypes: [{required: true, message: '请选择支持的配送方式', trigger: 'change'}],
  deliveryScope: [{required: true, message: '请选择配送范围', trigger: 'change'}],
  deliveryPrice: [{required: true, message: '请输入配送费金额', trigger: 'change'}],
  deliveryFreeThresholdPrice: [
    {
      required: true,
      message: '请输入免配送费门槛金额',
      trigger: 'blur'
    }
  ]
}

const computedMeatUnitPrice = computed({
  get() {
    return Number(fenToYuan(formData.value.meatUnitPrice))
  },
  set(value) {
    formData.value.meatUnitPrice = yuanToFen(value)
  }
})
const computedVegetableUnitPrice = computed({
  get() {
    return Number(fenToYuan(formData.value.vegetableUnitPrice))
  },
  set(value) {
    formData.value.vegetableUnitPrice = yuanToFen(value)
  }
})
const computedConsumeThresholdPrice = computed({
  get() {
    return Number(fenToYuan(formData.value.consumeThresholdPrice))
  },
  set(value) {
    formData.value.consumeThresholdPrice = yuanToFen(value)
  }
})
const computedDeliveryPrice = computed({
  get() {
    return Number(fenToYuan(formData.value.deliveryPrice))
  },
  set(value) {
    formData.value.deliveryPrice = yuanToFen(value)
  }
})
const computedDeliveryFreeThresholdPrice = computed({
  get() {
    return Number(fenToYuan(formData.value.deliveryFreeThresholdPrice))
  },
  set(value) {
    formData.value.deliveryFreeThresholdPrice = yuanToFen(value)
  }
})
const computedDailyOrderNoLimit = computed({
  get() {
    return formData.value.maxDailyOrders === -1
  },
  set(value) {
    formData.value.maxDailyOrders = value ? -1 : 200
  }
})

const onDeliveryScope = (e: any) => {
  if (e === 0) {
    formData.value.deliveryAddresses = []
  } else {
    formData.value.deliveryRadius = 0
    if (!formData.value.deliveryAddresses) {
      formData.value.deliveryAddresses = []
    }
    if (formData.value.deliveryAddresses.length === 0) {
      formData.value.deliveryAddresses.push({
        countyCode: '',
        detailAddress: ''
      })
    }
  }
}
const onRegionChange = (val: any, index: number) => {
  console.debug('onRegionChange: countyCode=' + val)
  formData.value.deliveryAddresses[index].detailAddress = ''
}
const addDeliveryAddress = () => {
  let needFill = false
  for (const deliveryAddress of formData.value.deliveryAddresses) {
    if (!deliveryAddress.countyCode || !deliveryAddress.detailAddress) {
      needFill = true
      break
    }
  }
  if (needFill) {
    message.warning('不能添加，请填写完整之前添加的配送地址')
    return
  }
  formData.value.deliveryAddresses.push({
    countyCode: '',
    detailAddress: ''
  })
}
const deleteDeliveryAddress = (index: number) => {
  if (formData.value.deliveryAddresses.length === 1) {
    message.warning('不能删除，至少需要一个配送地址')
    return
  }
  formData.value.deliveryAddresses.splice(index, 1)
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      DineConfigApi.write(formData.value)
    }
  })
}

const formLoading = ref(false)
const loadConfig = async () => {
  formLoading.value = true
  try {
    formData.value = await DineConfigApi.read()
  } finally {
    formLoading.value = false
  }
}
onMounted(async () => {
  if (checkRole(['shop_admin'])) {
    await loadConfig()
    return
  }
})
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="120px"
    label-position="right"
    v-loading="formLoading"
  >
    <el-form-item label="计价模式" prop="priceMode">
      <el-radio-group v-model="formData.priceMode">
        <el-radio v-for="(item, index) in priceModeMap" :key="index" :value="Number(index)">
          {{ item }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 按重量计价相关字段 -->
    <div v-if="formData.priceMode === 2">
      <el-form-item label="计价单位" prop="weightUnitName">
        <el-radio-group v-model="formData.weightUnitName">
          <el-radio
            v-for="item in weightUnitMap"
            :key="item"
            :value="item"
            :disabled="item === '两'"
          >
            {{ item }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="荤菜单价" prop="meatUnitPrice">
        <el-input-number
          v-model="computedMeatUnitPrice"
          :min="0"
          :step="1"
          :precision="2"
          controls-position="right"
          placeholder="0.00"
        >
          <template #suffix>元/{{ formData.weightUnitName || '?' }}</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="素菜单价" prop="vegetableUnitPrice">
        <el-input-number
          v-model="computedVegetableUnitPrice"
          :min="0"
          :step="1"
          :precision="2"
          controls-position="right"
          placeholder="0.00"
        >
          <template #suffix>元/{{ formData.weightUnitName || '?' }}</template>
        </el-input-number>
      </el-form-item>
    </div>

    <el-form-item label="最低消费金额" prop="consumeThresholdPrice">
      <el-input-number
        v-model="computedConsumeThresholdPrice"
        :min="0"
        :step="1"
        :precision="2"
        controls-position="right"
        placeholder="0.00"
      >
        <template #suffix>元</template>
      </el-input-number>
    </el-form-item>

    <el-form-item label="支持的服务模式" prop="deliveryTypes">
      <el-checkbox-group v-model="formData.deliveryTypes">
        <el-checkbox
          v-for="(item, index) in deliveryTypeMap"
          :key="index"
          :value="Number(index)"
          :disabled="Number(index) === 0"
        >
          {{ item }}
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <!-- 外卖相关字段 -->
    <div v-if="formData.deliveryTypes.includes(3)">
      <el-form-item label="配送费" prop="deliveryPrice">
        <el-input-number
          v-model="computedDeliveryPrice"
          :min="0"
          :step="1"
          :precision="2"
          controls-position="right"
          placeholder="0.00"
        >
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="免配送费门槛" prop="deliveryFreeThresholdPrice">
        <el-input-number
          v-model="computedDeliveryFreeThresholdPrice"
          :min="0"
          :step="1"
          :precision="2"
          controls-position="right"
          placeholder="0.00"
        >
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
    </div>
    <!-- 配送范围相关字段 -->
    <el-form-item label="配送范围" prop="deliveryScope">
      <el-radio-group v-model="formData.deliveryScope" @change="onDeliveryScope">
        <el-radio
          v-for="(item, index) in deliveryScopeMap"
          :key="index"
          :value="Number(index)"
          :disabled="Number(index) === 0"
        >
          {{ item }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <div v-if="formData.deliveryScope === 0">
      <el-form-item label="指定半径" prop="deliveryRadius">
        <el-input-number
          v-model="formData.deliveryRadius"
          :min="0"
          controls-position="right"
          placeholder="0.0"
        >
          <template #suffix>米</template>
        </el-input-number>
      </el-form-item>
    </div>
    <div v-if="formData.deliveryScope === 1" class="flex flex-col">
      <div v-for="(item, index) in formData.deliveryAddresses" :key="index">
        <el-form-item :label="'地址' + (index + 1)">
          <div class="flex w-100%">
            <RegionPicker
              v-model="item.countyCode"
              @change="
                (v) => {
                  onRegionChange(v, index)
                }
              "
              class="!w-180px"
            />
            <el-input
              v-model="item.detailAddress"
              placeholder="精确到楼栋或门牌号，门牌号用空格分隔"
              clearable
              class="ml-5px !w-240px"
            />
            <el-button type="warning" plain @click="deleteDeliveryAddress(index)" class="ml-20px"
            >删除
            </el-button>
            <el-button
              v-if="index === formData.deliveryAddresses.length - 1"
              type="primary"
              plain
              @click="addDeliveryAddress"
              class="ml-5px"
            >添加
            </el-button>
          </div>
        </el-form-item>
      </div>
    </div>

    <el-form-item label="主食要求" prop="requireStapleFood">
      <el-radio-group v-model="formData.requireStapleFood">
        <el-radio :value="true">必点，提示用户</el-radio>
        <el-radio :value="false">可选，不提示用户</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="餐盒要求" prop="requireKitchenware">
      <el-radio-group v-model="formData.requireKitchenware">
        <el-radio :value="true">必点，提示用户</el-radio>
        <el-radio :value="false">可选，不提示用户</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="日接单量" prop="maxDailyOrders">
      <el-radio-group v-model="computedDailyOrderNoLimit">
        <el-radio :value="true">不限</el-radio>
        <el-radio :value="false">上限</el-radio>
      </el-radio-group>
      <el-input-number
        v-if="!computedDailyOrderNoLimit"
        v-model="formData.maxDailyOrders"
        :min="-1"
        controls-position="right"
        placeholder="-1表示无限制"
        class="ml-10px"
      >
        <template #suffix>笔</template>
      </el-input-number>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm" :loading="formLoading">保存</el-button>
    </el-form-item>
  </el-form>
</template>
